package com.bafenyi.zh.bafenyilib.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.DownloadListener;
import android.webkit.WebIconDatabase;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;

import com.bafenyi.zh.bafenyilib.R;
import com.bafenyi.zh.bafenyilib.base.BFYBaseActivity;
import com.download.library.Extra;
import com.just.agentweb.AbsAgentWebSettings;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.DefaultDownloadImpl;
import com.just.agentweb.DefaultWebClient;
import com.just.agentweb.IAgentWebSettings;
import com.just.agentweb.WebChromeClient;
import com.just.agentweb.WebListenerManager;
import com.just.agentweb.WebViewClient;

public class WebActivity extends BFYBaseActivity {

    private LinearLayout ll_web;
    private ConstraintLayout rl_top;
    private RelativeLayout rl_network_error;
    private ImageView iv_back;
    private TextView tv_web_title;
    private Button btn_web_refresh;

    protected AgentWeb mAgentWeb;
    private String mUrl = "";


    @Override
    protected int getBaseLayout() {
        return R.layout.activity_web;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initBaseView(Bundle saveInstanceState) {
        mUrl = getIntent().getStringExtra("url");


        initTitle();

        ll_web = (LinearLayout) findViewById(R.id.ll_web);
        rl_top = (ConstraintLayout) findViewById(R.id.rl_feedback_top);
        rl_network_error = (RelativeLayout) findViewById(R.id.rl_network_error);
        iv_back = (ImageView) findViewById(R.id.iv_feedback_back);
        tv_web_title = (TextView) findViewById(R.id.tv_web_title);
        btn_web_refresh = (Button) findViewById(R.id.btn_web_refresh);
        if (mUrl.contains("privacy/index-cn")) {
            tv_web_title.setText("隐私政策");
        }else if (mUrl.contains("h5-chat")) {
            tv_web_title.setText("提点意见");
        }else if (mUrl.contains("privacy/service-protocol")) {
            tv_web_title.setText("用户协议");
        }else{
            tv_web_title.setText("更多精品Apps");
        }

        tv_web_title.setTextColor(ContextCompat.getColor(this , R.color.black));
        iv_back.setImageDrawable(ContextCompat.getDrawable(this , R.mipmap.ic_bfy_back));

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mAgentWeb.getWebCreator().getWebView().canGoBack()){
                    mAgentWeb.back();
                }else {
                    WebActivity.this.finish();
                }
            }
        });
        if(!isNetworkAvailable(this)){
            rl_network_error.setVisibility(View.VISIBLE);
        }else{
            rl_network_error.setVisibility(View.GONE);
        }
        btn_web_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isNetworkAvailable(WebActivity.this)){
                    rl_network_error.setVisibility(View.VISIBLE);
                }else{
                    rl_network_error.setVisibility(View.GONE);
                    mAgentWeb.getUrlLoader().reload();
                }
            }
        });

        WebIconDatabase.getInstance().open(getDir("icons",MODE_PRIVATE).getPath());
        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(ll_web, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setAgentWebWebSettings(getSettings())//设置 IAgentWebSettings。
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.layout_web_error, -1)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
//                .setWebLayout(new WebLayout(this))
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
                .interceptUnkownUrl() //拦截找不到相关页面的Scheme
                .createAgentWeb()
                .ready()
                .go(mUrl);
        mAgentWeb.getWebCreator().getWebView().setWebViewClient(new android.webkit.WebViewClient(){
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("111","shouldOverrideUrlLoading: "+url);
                if(url.endsWith(".apk")){
                    Toast.makeText(WebActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
    }

    @Override
    protected void initAnylayerShow() {

    }

    private boolean isNetworkAvailable(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = cm.getActiveNetworkInfo();
            if (null != info && info.isConnected() && info.isAvailable()) {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

    /**
     * @return IAgentWebSettings
     */
    public IAgentWebSettings getSettings() {
        return new AbsAgentWebSettings() {
            private AgentWeb mAgentWeb;

            @Override
            protected void bindAgentWebSupport(AgentWeb agentWeb) {
                this.mAgentWeb = agentWeb;
            }

            /**
             * AgentWeb 4.0.0 内部删除了 DownloadListener 监听 ，以及相关API ，将 Download 部分完全抽离出来独立一个库，
             * 如果你需要使用 AgentWeb Download 部分 ， 请依赖上 compile 'com.just.agentweb:download:4.0.0 ，
             * 如果你需要监听下载结果，请自定义 AgentWebSetting ， New 出 DefaultDownloadImpl，传入DownloadListenerAdapter
             * 实现进度或者结果监听，例如下面这个例子，如果你不需要监听进度，或者下载结果，下面 setDownloader 的例子可以忽略。
             * @param webView
             * @param downloadListener
             * @return WebListenerManager
             */
            @Override
            public WebListenerManager setDownloader(WebView webView, DownloadListener downloadListener) {
                return super.setDownloader(webView, DefaultDownloadImpl.create( WebActivity.this, webView, this.mAgentWeb.getPermissionInterceptor()));
            }
        };
    }

    private void initTitle() {
        setBarForBlack();
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Log.e("123456","shouldOverrideUrlLoading: "+request.getUrl().toString());

//            return super.shouldOverrideUrlLoading(view, request);
            return true;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.e("111","shouldOverrideUrlLoading: "+url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //do you  work
            Log.e("Info", "url: "+url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Log.e("Info", "onPageFinishedurl: "+url);
        }
    };
    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
//            Log.e("1908","")
            return super.onConsoleMessage(consoleMessage);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //do you work
//            Log.i("Info","onProgress:"+newProgress);
            super.onProgressChanged(view , newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            super.onReceivedIcon(view, icon);
            Log.e("1905","onReceivedIcon");
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        Log.i("Info", "onResult:" + requestCode + " onResult:" + resultCode);
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    protected void onPrepareCreate() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAgentWeb.getWebLifeCycle().onDestroy();
    }

}
